package com.allwees.bs.c.module.order.service.impl;

import com.allwees.bs.c.module.order.context.processor.OrderRefundPostProcessor;
import com.allwees.bs.c.module.order.dto.OrderDTO;
import com.allwees.bs.c.module.order.dto.OrderItemDTO;
import com.allwees.bs.c.module.order.entity.OrderItemEntity;
import com.allwees.bs.c.module.order.mapper.OrderMapper;
import com.allwees.bs.c.module.order.repository.OrderItemRepository;
import com.allwees.bs.c.module.order.req.OrderApplyRefundReq;
import com.allwees.bs.c.module.order.service.IOrderItemService;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import com.allwees.core.cache.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderItemServiceImpl implements IOrderItemService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemRepository orderItemRepository;
    @Autowired
    private OrderRefundPostProcessor orderRefundPostProcessor;

    @Override
    @Transactional
    public OrderDTO userRequestRefundOrder(String userUuid, String orderUuid, OrderApplyRefundReq req) {
        if (!RedisUtil.setNx(userUuid + "_refund", "", 4000)) {
            throw BusinessException.getInstance(ResultEnum.EXCEED_ACCESS_LIMIT);
        }
        orderRefundPostProcessor.doApplyRefund(req.getOrderItemUuid(), userUuid, req);
        return this.orderMapper.toDto(orderUuid);
    }

    @Override
    public List<OrderItemDTO> findOrderItems(String orderUuid) {
        List<OrderItemEntity> orderItems = orderItemRepository.findOrderItems(orderUuid);
        List<OrderItemDTO> orderItemDtos = new ArrayList<>();
        orderItems.forEach(orderItem -> orderItemDtos.add(new OrderItemDTO(orderItem)));
        return orderItemDtos;
    }

    @Override
    public void updateRefundChannelUuidByOrderItemUuid(String orderItemUuid, String refundChannelUuid) {
        OrderItemEntity orderItemEntity = orderItemRepository.findByUuid(orderItemUuid);
        if (orderItemEntity == null) {
            throw new RuntimeException("orderItemUuid(" + orderItemUuid + ") cannot be fund.");
        }

        orderItemEntity.setRefundChannelUuid(refundChannelUuid);
        orderItemRepository.save(orderItemEntity);
    }

    @Override
    public OrderItemEntity findByOrderItemUuid(String orderItemUuid) {
        return orderItemRepository.getByUuid(orderItemUuid);
    }
}
